package com.wangshb.upms.core.spring.security;

import com.wangshb.upms.core.utils.AssertUtil;
import com.wangshb.upms.core.utils.JwtTokenUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.www.NonceExpiredException;
import org.springframework.util.Assert;


public class JwtAuthenticationProvider implements AuthenticationProvider {


    /**
     * 获取用户信息，校验token是否有效
     *
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        AssertUtil.isInstanceOf(JwtAuthenticatioToken.class, authentication,
                () -> "authentication 对象不是 JwtAuthenticatioToken 类型!");

        JwtAuthenticatioToken jwtAuthenticatioToken = (JwtAuthenticatioToken) authentication;
        AssertUtil.hasLength(jwtAuthenticatioToken.getToken(), "token认证信息不能为空");


        String token = jwtAuthenticatioToken.getToken();
        // 校验token是否有效
        if (JwtTokenUtils.isTokenExpired(token)) {
            throw new NonceExpiredException("Token 失效");
        }

        return JwtTokenUtils.getAuthenticationeFromToken(token);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtAuthenticatioToken.class.isAssignableFrom(authentication);
    }
}